<template>
  <el-upload
    ref="upload"
    class="uploader"
    :action="BASE_URL + uploadUrl"
    :show-file-list="showFileList"
    :on-success="handleUploadSuccess"
    :limit="limit"
    :on-exceed="handleExceed"
    :before-upload="beforeUpload"
    :headers="headers"
  >
    <el-image v-if="imageSrc" :src="imageSrc" :class="imageClass" fit="cover" class="avatar" />
    <el-icon v-else id="uploadIcon" class="el-upload" :class="imageClass">
      <Plus />
    </el-icon>
  </el-upload>
</template>

<script setup>
import { ref, watch } from "vue";
import { BASE_URL } from "@/utils/request";
import { ElMessage } from "element-plus";
import { genFileId } from "element-plus";
import { useApp } from "@/pinia/modules/app";

const headers = {
  token: useApp().authorization.token // 从pinia中获取token，在进行文件上传的时候将token设置到请求头中
};

const props = defineProps({
  imageUrl: {
    type: String
  },
  uploadUrl: {
    type: String,
    default: "/admin/product/image/upload"
  },
  showFileList: {
    type: Boolean,
    default: false
  },
  limit: {
    type: Number,
    default: 1
  },
  imageClass: {
    type: String,
    default: "avatar-uploader-icon"
  },
  businessId: {
    type: Number
  }
});
const imageSrc = ref(props.imageUrl);

const emits = defineEmits(["uploadSuccess"]);

// 监听父组件的图片地址
watch(() => props.imageUrl, newVal=> {
  imageSrc.value = newVal;
})

// ===================== 上传操作 ==========================
// 图片对象
let upload = ref();
// 图片替换
const handleExceed = (files) => {
  upload.value.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  upload.value.handleStart(file);
};
// 上传前图片校验
const beforeUpload = (rawFile) => {
  const suffix = rawFile.name.substring(rawFile.name.lastIndexOf(".") + 1);
  const reg = /^(gif|jpg|jpeg|png)$/;
  if (!reg.test(suffix)) {
    ElMessage.warning("图片格式不支持，支持的格式：png/jpg/jpeg/gif");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不能超过 2MB！");
    return false;
  }
  return true;
};
// 图像上传成功以后的事件处理函数
const handleUploadSuccess = (response, uploadFile) => {
  if (response.code !== 200) return;
  imageSrc.value = response.data;
  upload.value.clearFiles(); //上传成功之后清除历史记录,解决上传控件第二次提交无效问题
  emits("uploadSuccess", response.data, props.businessId);
};
</script>

<style scoped>
.uploader .avatar {
  max-width: 160px;
  max-height: 160px;
  display: block;
  border-radius: 6px;
}

.uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

#uploadIcon {
  color: #8c939d;
}

.avatar-uploader-icon {
  font-size: 28px;
  width: 80px;
  height: 80px;
}
</style>
